// src/store.js
import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';
import api from '@/api/api';
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    username: '',
    avatar: '',
    favorites: [] ,
    
  },
  mutations: {
    SET_USER_INFO(state, userInfo) {
        state.username = userInfo.username;
        state.avatar = userInfo.avatar;
      },
    LOGOUT(state) {
      state.username = '';
      state.avatar = '';
    },
    DELETE_POST(state, postId) {
        state.posts = state.posts.filter(post => post.id !== postId);
      },
    SET_FAVORITES(state, favorites) {
        state.favorites = favorites.map(item => item.postId); 
      },
      ADD_FAVORITE(state, postId) {
        if (!state.favorites.includes(postId)) {
          state.favorites.push(postId);
        }
      },
      REMOVE_FAVORITE(state, postId) {
        state.favorites = state.favorites.filter(id => id !== postId);
      }
  },
  actions: {
    setUserInformation({ commit }, userInfo) {
        commit('SET_USER_INFO', userInfo);
      },
    logout({ commit }) {
      commit('LOGOUT');
    },

    fetchFavorites({ commit, state }) {
      return api.getFavorites(state.username)
        .then(response => {
          commit('SET_FAVORITES', response.data);
          return response.data;
        });
    },
    // 添加收藏
    addFavorite({ commit, state }, postId) {
      return api.addFavorite(state.username, postId)
        .then(response => {
          commit('ADD_FAVORITE', postId);
          return response;
        });
    },
    // 取消收藏
    removeFavorite({ commit, state }, postId) {
      return api.removeFavorite(state.username, postId)
        .then(response => {
          commit('REMOVE_FAVORITE', postId);
          return response;
        });
    },
  },
  getters: {
    getUsername: state => state.username,
    getAvatar: state => state.avatar,
    isPostCollected: (state) => (postId) => state.favorites.includes(postId)
  },
  plugins: [
    createPersistedState({
      storage: window.localStorage,
      paths: ['username', 'avatar', 'favorites']
    })
  ]
});